package com.lw.leetcode.arr.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 54. 螺旋矩阵
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/27 13:55
 */
public class SpiralOrder {

    public List<Integer> spiralOrder2(int[][] matrix) {
        List<Integer> all = new ArrayList<>();
        int xl = matrix.length;
        if (xl == 0) {
            return all;
        }
        int yl = matrix[0].length;
        int xs = 0;
        int ys = 0;
        List<Integer> aa = aa(matrix, xs++, --xl, ys++, --yl);

        while (!aa.isEmpty()) {
            all.addAll(aa);
            aa = aa(matrix, xs++, --xl, ys++, --yl);
        }

        return all;
    }

    public List<Integer> aa(int[][] matrix, int xs, int xe, int ys, int ye) {
        List<Integer> list = new ArrayList<>();
        if (xs > xe || ys > ye) {
            return list;
        }
        if (xs == xe && ys == ye && xs == ys) {
            list.add(matrix[xs][ys]);
            return list;
        }

        for (int i = ys; i < ye; i++) {
            list.add(matrix[xs][i]);

        }
        if (xs == xe) {
            list.add(matrix[xs][ye]);
            return list;
        }
        for (int i = xs; i < xe; i++) {
            list.add(matrix[i][ye]);

        }
        if (ys == ye) {
            list.add(matrix[xe][ye]);
            return list;
        }
        for (int i = ye; i > ys; i--) {
            list.add(matrix[xe][i]);
        }
        for (int i = xe; i > xs; i--) {
            list.add(matrix[i][ys]);
        }
        return list;
    }


    public int[] spiralOrder(int[][] matrix) {
        int xl = matrix.length;
        if (xl == 0) {
            return new int[0];
        }
        int yl = matrix[0].length;
        int xs = 0;
        int ys = 0;
        List<Integer> all = new ArrayList<>();
        List<Integer> aa = aa(matrix, xs++, --xl, ys++, --yl);

        while (!aa.isEmpty()) {
            all.addAll(aa);
            aa = aa(matrix, xs++, --xl, ys++, --yl);
        }

        int size = all.size();

        int[] arr = new int[size];

        for (int i = 0; i < size; i++) {
            arr[i] = all.get(i);
        }
        return arr;
    }


}
